<template>
  <div class="user-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- :gutter设置col之间的间隙 -->
      <el-row :gutter="15">
        <!-- :span设置该col所占的宽度 -->
        <!-- 搜索区域start -->
        <el-col :span="7">
          <!-- v-model绑定搜索参数 -->
          <el-input
            placeholder="请输入搜索内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <!-- 调用getUserList方法查询内容 -->
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addDialogFormVisible = true"
            >添加用户</el-button
          >
        </el-col>
        <!-- 搜索区域end -->
        <!-- 用户列表区域start -->
        <el-col>
          <el-table :data="userList" border stripe style="width: 100%">
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="username" label="姓名"></el-table-column>
            <el-table-column prop="mobile" label="手机"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="role_name" label="角色"></el-table-column>
            <el-table-column label="状态" width="65">
              <!-- scope.row作用域插槽获取当前行的数据 -->
              <template v-slot="scope">
                <!-- {{scope.row.mg_state}} -->
                <el-switch
                  v-model="scope.row.mg_state"
                  @change="userStatusChanged(scope.row)"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button-group>
                  <el-button
                    type="warning"
                    icon="el-icon-edit"
                    size="mini"
                    @click="
                      editDialogFormVisible = true
                      showEditDialogForm(scope.row.id)
                    "
                  ></el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="deleteUser(scope.row)"
                  ></el-button>
                  <el-tooltip
                    effect="dark"
                    content="分配角色"
                    placement="top"
                    :enterable="false"
                  >
                    <el-button
                      type="success"
                      icon="el-icon-setting"
                      size="mini"
                    ></el-button>
                  </el-tooltip>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <!-- 用户列表end -->
      </el-row>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 新增用户对话框区域start，:visible.sync对话框的打开和关闭-->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogFormVisible"
      width="500px"
    >
      <!-- model绑定数据，rules添加验证规则 -->
      <el-form
        :model="addUserForm"
        :rules="addUserFormRules"
        ref="addUserFormRef"
        label-width="70px"
      >
        <!-- prop:验证规则名字的声明，v-model绑定addUserForm数组中的数据  -->
        <el-form-item label="用户名:" prop="username">
          <el-input
            v-model="addUserForm.username"
            maxlength="10"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="addUserForm.password" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="addUserForm.email" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input
            v-model="addUserForm.mobile"
            maxlength="11"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="addUser">新 增</el-button>
        <el-button type="primary" @click="resetAddUserForm">重 置</el-button>
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增用户对话框区域end -->

    <!-- 修改用户对话框start -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogFormVisible"
      @close="resetEditUserForm()"
      width="500px"
    >
      <el-form
        :model="editUserForm"
        :rules="editUserFormRules"
        ref="editUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名:" prop="username">
          <el-input :value="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="editUserForm.email" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机:" prop="mobile">
          <el-input
            v-model="editUserForm.mobile"
            clearable
            maxlength="11"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="editUser()">修 改</el-button>
        <!-- <el-button type="primary" @click="resetEditUserForm">重 置</el-button> -->
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户对话框end -->
  </div>
</template>

<script>
export default {
  data() {
    // 邮箱校验规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则
      const regEmail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      // 验证邮箱是否合法
      if (regEmail.test(value)) return callback()
      // 不合法返回一个错误提示
      return callback(new Error('请输入合法的邮箱'))
    }
    // 手机号码校验规则
    var checkPhone = (rule, value, callback) => {
      // 手机的验证规则
      const regPhone = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/
      // 验证手机是否合法
      if (regPhone.test(value)) return callback()
      // 不合法返回一个错误提示
      return callback(new Error('请输入合法的手机号码'))
    }
    return {
      // 查询用户列表的参数对象
      queryInfo: {
        // 查询的参数
        query: '',
        // 显示第几页
        pagenum: 1,
        // 每页显示几条数据
        pagesize: 10,
      },
      // 用户列表
      userList: [],
      // 用户总数量
      total: 0,
      // 控制新增用户对话框的显示与隐藏
      addDialogFormVisible: false,
      // 控制修改用户对惶恐的显示与隐藏
      editDialogFormVisible: false,
      // 控制删除用户提示框的显示与隐藏
      dialogVisible: false,
      // 存储要删除的单行的信息
      delUserInfo: {},
      // 存储用户信息新旧值
      editNewVal: {},
      editOldVal: {},
      // 新增用户表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 修改用户表单数据
      editUserForm: {
        username: '',
        email: '',
        mobile: '',
      },
      // 添加用户表单数据验证规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '用户名长度在3~10之间' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在6到16之间' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // validator表单的自定义验证规则
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' },
        ],
      },
      // 修改用户验证规则
      editUserFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // validator表单的自定义验证规则
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(data)
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      this.userList = data.data.users
      this.total = data.data.total
    },
    // 设置每页显示多少条数据,每次切换会传递一个当前显示的数量
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 切换页码,每次触发会传递一个当前的页面
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 切换用户的状态，userStatusInfo接收一个用户信息
    async userStatusChanged(userStatusInfo) {
      console.log(userStatusInfo.mg_state)
      // put发送修改请求，传递要修改该列的id和状态
      const { data } = await this.$http.put(
        `users/${userStatusInfo.id}/state/${userStatusInfo.mg_state}`
      )
      // console.log(data)
      // 判断状态是否设置成功,!==200代表设置失败
      if (data.meta.status !== 200) {
        // 将页面的switch按钮重置
        userStatusInfo.mg_state = !userStatusInfo.mg_state
        // 提示设置失败错误信息
        return this.$message.error(data.meta.msg)
      }
      // 提示成功信息
      this.$message.success(data.meta.msg)
    },
    // 重置用户添加表
    resetAddUserForm() {
      // 通过this.$refs获取表单项调用resetFields()方法对整个表单进行重置
      this.$refs.addUserFormRef.resetFields()
    },
    // 重置修改用户表
    resetEditUserForm() {
      this.$refs.editUserFormRef.resetFields()
    },
    // 新增用户按钮
    addUser() {
      // validate对整个表单进行校验
      this.$refs.addUserFormRef.validate(async (valid) => {
        // 如果校验失败直接return
        if (valid === false) return this.$message.error('添加失败')
        // 添加用户传递this.addUserForm中的数据
        const { data } = await this.$http.post('users', this.addUserForm)
        // console.log(data)
        // 判断用户是否添加成功
        if (data.meta.status !== 201) return this.$message.error(data.meta.msg)
        this.$message.success(data.meta.msg)
        // 添加成功后清空表单
        this.resetAddUserForm()
        // 添加成功后关闭对话框
        this.addDialogFormVisible = false
        // 刷新用户列表
        this.getUserList()
      })
    },
    // 查询修改用户的信息
    async showEditDialogForm(id) {
      const { data } = await this.$http.get('users/' + id)
      // 判断是否成功获取到数据信息
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      // this.$message.success('成功获取要修改的用户信息')
      // 将用户信息保存到editUserForm表所绑定的数据中
      this.editUserForm = data.data
      console.log('当前用户id为：' + this.editUserForm.id)
    },
    // 修改用户按钮
    editUser() {
      // validate对表单进行校验
      this.$refs.editUserFormRef.validate(async (valid) => {
        // console.log(valid)
        // 如果校验失败直接return
        if (valid === false) return this.$message.error('修改失败')
        // put执行修改，传递当前的id和editUserForm表中的email和mobile
        const { data } = await this.$http.put(`users/${this.editUserForm.id}`, {
          email: this.editUserForm.email,
          mobile: this.editUserForm.mobile,
        })
        console.log(data)
        // 判断是否修改成功
        if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
        // 提示修改成功
        this.$message.success(data.meta.msg)
        // 成功后关闭修改用户对话框
        this.editDialogFormVisible = false
        // 重新获取用户列表
        this.getUserList()
      })
    },
    // 删除用户按钮
    deleteUser(delUserInfo) {
      // console.log(delUserInfo)
      // 使用elementui中的$confirm
      this.$confirm(`是否删除姓名为${delUserInfo.username}的用户？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 调用delete执行删除
          const { data } = await this.$http.delete(`users/${delUserInfo.id}`)
          // 判断是否删除成功
          if (data.meta.status !== 200) {
            return this.$message.error(data.meta.msg)
          }
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          // 刷新用户列表
          this.getUserList()
        })
        .catch(() => {
          this.$message('已取消删除')
        })
    },
  },
  created() {
    this.getUserList()
  },
}
</script>

<style lang="less" scoped>
.user-container {
  margin: 10px;
  .el-table {
    margin-top: 15px;
    .el-button-group {
      .el-button {
        margin-right: 8px;
      }
    }
  }
  .el-pagination {
    margin-top: 15px;
  }
}
</style>
